package com.jht.bletool.entity;

import android.bluetooth.BluetoothDevice;

import com.jht.bletool.util.BaseUtils;

public class BleDevice {

    private BluetoothDevice device;
    private int rssi;
    private byte[] scanRecord;
    private boolean isChangeRSSI = false;

    public BleDevice() {
    }

    public BleDevice(BluetoothDevice device, int rssi, byte[] scanRecord) {
        this.device = device;
        this.rssi = rssi;
        this.scanRecord = scanRecord;
    }

    public BluetoothDevice getDevice() {
        return device;
    }

    public void setDevice(BluetoothDevice device) {
        this.device = device;
    }

    public int getRssi() {
        return rssi;
    }

    public void setRssi(int rssi) {
        this.rssi = rssi;
    }

    public byte[] getScanRecord() {
        return scanRecord;
    }

    public void setScanRecord(byte[] scanRecord) {
        this.scanRecord = scanRecord;
    }

    public boolean isChangeRSSI() {
        return isChangeRSSI;
    }

    public void setChangeRSSI(boolean changeRSSI) {
        isChangeRSSI = changeRSSI;
    }


    //增加对广播数据的处理
    public String getMachineType(){
        if (scanRecord == null){
            return "null";
        }
        int currentLen = 0;
        for(int i=0;i<scanRecord.length;){
            int fragmentLen = scanRecord[i];
            if (fragmentLen == 0){
                break;
            }
            int adType = scanRecord[i+1];
            if (adType == 0x16){
                if (fragmentLen<6){
                    return "广播数据格式不全,解析失败";
                }
                //1.获取服务特征
                byte[] service_uuid = new byte[]{scanRecord[i+2],scanRecord[i+3]};
                String hexString_service_uuid = getHexString(service_uuid);
                //2.解析flag 和 支持的机种
                FitnessMachineTypeField fitnessMachineTypeField = new FitnessMachineTypeField(new byte[]{scanRecord[i+4],scanRecord[i+5],scanRecord[i+6]});
                return fitnessMachineTypeField.convert2String();
            }else {
                i = i+fragmentLen+1;
            }
        }
        return "null";
    }

    public static String getHexString(byte[] data){
        StringBuilder sb = new StringBuilder();
        for (int i = data.length-1; i>=0; i--){
            String str = Integer.toHexString(BaseUtils.byte1ToInt(data[i]));
            if (str.length() == 1){
                str = "0"+str;
            }
            sb.append(str);
        }
        return sb.toString();
    }
}
